package com.lagou.java.factory;

import com.lagou.java.annotation.Autowired;
import com.lagou.java.annotation.Component;
import com.lagou.java.utils.TransactionManagerUtils;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Set;

@Component("proxyFactory")
public class ProxyFactory {

    @Autowired
    private TransactionManagerUtils transactionManagerUtils;

    public void setTransactionManagerUtils (TransactionManagerUtils transactionManagerUtils ) {
        this.transactionManagerUtils = transactionManagerUtils;
    }

    /**
     * Jdk动态代理
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJdkProxy (Object obj, Set<String> proxyMethodNames) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;
                if(proxyMethodNames.contains(method.getName())) {
                    try {
                        transactionManagerUtils.beginTransaction();
                        invoke = method.invoke(obj, args);
                        transactionManagerUtils.commintTransaction();
                    } catch (Exception e) {
                        e.printStackTrace();
                        transactionManagerUtils.rollbackTransaction();
                        //抛出异常便于上层servlet捕获
                        throw e;
                    }
                } else {
                    invoke = method.invoke(obj, args);
                }
                return invoke;
            }
        });
    }

    public Object getCglicProxy (Object obj, Set<String> proxyMethodNames) throws Exception {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {

            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object invoke = null;
                if(proxyMethodNames.contains(method.getName())) {
                    try {
                        transactionManagerUtils.beginTransaction();
                        invoke = method.invoke(obj, objects);
                        transactionManagerUtils.commintTransaction();
                    } catch (Exception e) {
                        e.printStackTrace();
                        transactionManagerUtils.rollbackTransaction();
                        //抛出异常便于上层servlet捕获
                        throw e;
                    }
                } else {
                    invoke = method.invoke(obj, objects);
                }
                return invoke;
            }
        });
    }
}
